package com.paas.demo.shiro;

import com.plat.paas.core.RedisUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;

import java.io.Serializable;
/**
 * @ClassName : ShiroSessionRedisDao
 * @Description : Shiro Session Redis持久化类
 * @author : pengjie
 * @email  : 627799251@qq.com
 * @version
 * @Date : 2019/1/21 12:57
*/
public class ShiroSessionRedisDao extends EnterpriseCacheSessionDAO {

    private static String RedisSessionTableKey = "shiro:session:table";

    @Override
    protected Serializable doCreate(Session session) {
        System.out.println("====== doCreate :" + session + " ===============");

        Serializable sessionId = super.doCreate(session);

        RedisUtil.hsetItem(RedisSessionTableKey, sessionId.toString(), session);

        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = RedisUtil.hgetItem(RedisSessionTableKey, sessionId.toString(), Session.class);

        if (session != null){
            System.out.println("====== doReadSession redis :" + sessionId + " ===============");
            return session;
        }
        System.out.println("====== doReadSession  :" + sessionId + " ===============");
        return super.doReadSession(sessionId);
    }

    @Override
    protected void doUpdate(Session session) {
        System.out.println("====== doUpdate :" + session + " ===============");

        RedisUtil.hsetItem(RedisSessionTableKey, session.getId().toString(), session);

        super.doUpdate(session);
    }

    @Override
    protected void doDelete(Session session) {
        System.out.println("====== doDelete :" + session + " ===============");

        RedisUtil.hdelItem(RedisSessionTableKey, session.getId().toString());

        super.doDelete(session);
    }
}
